import React, {Component, PropTypes} from 'react';

import Relay from "react-relay";

import FindServiceDicListMutation from "../mutation/FindServiceDicListMutation";
import createEnterpriseServiceDicMutation from '../mutation/CreateEnterpriseServiceDicMutation';
import deleteEnterpriseServiceDicMutation from '../mutation/DeleteEnterpriseServiceDicMutation';

import _key from '../../../util/ReactKey';
import Util from "../../../util/Util"
import classNames from 'classnames';
import {_Input, _Modal, _Select, _message, _Tag, _Tooltip, _Button, _notification, _Icon} from 'ANT_DE';

const Input = _Input, Modal = _Modal,
    Tag = _Tag, Tooltip = _Tooltip,
    _Option = _Select.Option,
    message = _message,
    Button = _Button,
    notification = _notification,
    Icon = _Icon;


export default class A extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputVisible: false,   // 服务类型添加按钮与输入按钮切换
            inputVisible_1: false,  // 服务类型2 添加与删除按钮切换
            newTagName: "",        // 服务类型添加时value值

            is_modal_enterType: false, //企业类型选择窗口显示

            //三份数组，三份选中状态
            enType_oneActive: 0,
            enType_twoActive: null,
            enType_ThreeActive: [],

            OneList: [],
            TwoList: [],
            ThreeList: [],

            //显示的勾选项
            CheckedList: [],
            //需要发送的数据
            SubData: "",

            //显示的企业类型
            showEnType: ""
        };

        this.handleModaEnterTypeClick = this.handleModaEnterTypeClick.bind(this);
        this.conmirBtn = this.conmirBtn.bind(this);
        this.handleInputConfirm = this.handleInputConfirm.bind(this);
        this.oneTypeSelect = this.oneTypeSelect.bind(this);

        this.EnterType_ok = this.EnterType_ok.bind(this);
        this.EnterType_cancel = this.EnterType_cancel.bind(this);

        //整理级别数组
        this.upDataTwoList = this.upDataTwoList.bind(this);
        this.upDataThreeList = this.upDataThreeList.bind(this);

        this.handleEnTypeThreeActive = this.handleEnTypeThreeActive.bind(this);
        this.handleDeleteService = this.handleDeleteService.bind(this);

        this.num = 0;
    }

    //liu _ callback
    componentWillMount() {
    }

    // 点击弹框sdrtasd
    handleModaEnterTypeClick(is_modal_enterType) {
        this.setState({is_modal_enterType});
        Relay.Store.commitUpdate(
            new FindServiceDicListMutation({
                enid:'-1'
            }),
            {
                onFailure: () => {
                    alert('请求失败');
                },
                onSuccess: (response) => {
                    let data = response.findAllServiceDicList.data.dicList;
                    this.setState({
                        OneList: data
                    }, () => {
                        // 整理二级菜单
                        data && this.upDataTwoList(0);
                    });
                }
            }
        );
    }

    //负责根据一级列表更新二级列表
    upDataTwoList(index) {
        let {OneList} = this.state, TwoList = [];

        for (let key in OneList[index].subList) {
            TwoList.push(OneList[index].subList[key]);
        }

        this.setState({TwoList})
    }

    //负责根据二级列表更新三级列表
    upDataThreeList(_index) {
        let ThreeList = [],
            subList = this.state.TwoList[_index].subList;

        for (let key in subList) {
            ThreeList.push(subList[key])
        }
        console.log(subList);
        this.setState({
            ThreeList
        })
    }


    /*
     * 选中
     * */

    //企业类型选中 更新key
    oneTypeSelect(enType_oneActive) {
        this.upDataTwoList(enType_oneActive);
        // 选中清空三级列表
        this.state.ThreeList = [];
        // 更改二级和三级选中的.
        this.state.enType_twoActive = null;
        this.state.enType_ThreeActive = [];
        this.state.CheckedList = [];

        this.setState({enType_oneActive});
    }

    // 二级菜单 选中与更新key
    handleEnTypeTwoActive(enType_twoActive) {
        console.log("二级选中");

        // 传两个 一级 和二级 更新三级
        this.upDataThreeList(enType_twoActive);
        this.setState({enType_twoActive: enType_twoActive});

    }

    // 三级菜单主要服务选中函数
    handleEnTypeThreeActive(enType_ThreeActive) {
        // 生成当前选中数组 去二级里边
        const data = this.state.ThreeList[enType_ThreeActive],
            CheckedList = this.state.CheckedList,
            ThreeList = this.state.enType_ThreeActive;

        //加入当前状态s
        let Arr = ThreeList,
            of_index = ThreeList.indexOf(data.dicId);


        if (of_index > -1) {
            console.log("选中了");
            Arr.splice(of_index, 1);


            CheckedList.splice(of_index, 1);

            this.setState({enType_ThreeActive: Arr, CheckedList: CheckedList});

        } else {
            console.log("没选中");
            Arr.push(data.dicId);
            CheckedList.push(data);
            this.setState({enType_ThreeActive: Arr, CheckedList: CheckedList});
        }
        console.log(this.state.CheckedList);
    }

    //input与button 显示与隐藏 true || false
    handleInputShowClick(inputVisible, e) {
        this.setState({inputVisible}, () => {
            this.input.focus()
        });
    }

    handleInputShowClick_1(inputVisible_1, e) {
        this.setState({inputVisible_1}, () => {
            this.input_1.focus()
        });
    }

    //  input新建标签value改变
    handleNewTagChange(e) {
        this.setState({newTagName: e.target.value})
    }

    //  input新建标签提交方法
    handleInputConfirm(parentId, level) {
        // 验证name.length  是否重名  新增的length
        let value = this.state.newTagName,
            x_List = level === 2 ? this.state.TwoList : this.state.ThreeList,
            end = () => {
                level === 2 ? this.setState({newTagName: "", inputVisible: false}) :
                    this.setState({newTagName: "", inputVisible_1: false})
            };

        if (value.length > 5) {
            message.warning("添加此服务名称不可超过5个字符");
            end();
            return;
        } else if (value.indexOf(" ") !== -1) {
            message.warning("名称含有非法字符,请更换");
            end();
            return;
        } else if (value === "") {
            end();
            return;
        }
        for (let item of x_List) {
            if (value == item.name) {
                message.warning("当前服务名称不可与其他名称相同");
                end();
                return;
            }
        }

        let loading = message.loading("正在添加，请稍等", 0);
        // // Relay.Store.createEnterpriseServiceDicMutation
        Relay.Store.commitUpdate(
            new createEnterpriseServiceDicMutation({
                enid:"0",
                name: value,
                parentId: parentId,
                level: level,
            }),
            {
                onFailure: (errcode) => {
                    notification.open({
                        message: '网络错误',
                        description: `网络出现错误，请您刷新页面重试，或报告网站管理员`,
                        placement: "bottomLeft",
                        icon: <Icon type="smile-circle" style={{color: '#ff6565', fontSize: 35, marginTop: 10}}/>,
                    });
                },
                onSuccess: (response) => {
                    loading();
                    const data = response.createEnterpriseServiceDic.data;
                    notification.open({
                        message: data.value,
                        description: data.errorCode === "0" ? `您已成功添加${level - 1}级主要服务，名称为${value}，此服务会一直为您保存。` :
                            `添加${level - 1}级服务失败，请仔细阅读添加服务规则，提醒并检查添加服务个数。`,
                        placement: "bottomLeft",
                        icon: <Icon type="smile-circle" style={{
                            color: `#${data.errorCode != 0 ? "ff6565" : "108ee9"}`,
                            fontSize: 35,
                            marginTop: 10
                        }}/>,
                    });
                    if (data.errorCode === "0") {
                        data.enterpriseServiceDic.subList = [];
                        x_List.push(data.enterpriseServiceDic);

                        //此处需要更改两处状态，因为点击二级菜单时需要从二级下获取三级列表;
                        if (level === 2) {
                            let OneList = this.state.OneList;
                            OneList[this.state.enType_oneActive].subList.push(data.enterpriseServiceDic);
                            this.setState({TwoList: x_List})
                        } else {

                            let TwoList = this.state.TwoList;
                            //更新二级
                            TwoList[this.state.enType_twoActive].subList.push(data.enterpriseServiceDic);
                            //更新三级
                            this.setState({ThreeList: x_List})
                        }

                        console.log(x_List);
                    }
                }
            }
        );

        end();
    }


    //删除
    handleDeleteService(index, level, e) {
        e.stopPropagation();
        console.log("触发删除");
        // // Relay.Store.createEnterpriseServiceDicMutation
        let state = this.state,
            data = level === 2 ? state.TwoList : state.ThreeList,
            oneActive = this.state.enType_oneActive,
            twoActive = this.state.enType_twoActive,
            CheckedList = this.state.CheckedList;

        Relay.Store.commitUpdate(
            new deleteEnterpriseServiceDicMutation({
                dicId: data[index].dicId,
                enid: "0"
            }),

            {
                onFailure: (error) => {
                    notification.open({
                        message: '网络错误',
                        description: `网络出现错误，请您刷新页面重试，或报告网站管理员`,
                        placement: "bottomLeft",
                        icon: <Icon type="smile-circle" style={{color: '#ff6565', fontSize: 35, marginTop: 10}}/>,
                    });
                },
                onSuccess: (response) => {
                    const _data = response.deleteEnterpriseServiceDic.data,
                        removeActiveItem = this.state.ThreeList[index],
                        removeTwoDicId = data[index].dicId;
                    if (_data.errorCode == 0) {
                        message.success(`已成功删除`);
                        data.splice(index, 1);      //固定更新二级和三级list列表.
                        if (level === 2) {
                            let OneList = this.state.OneList,
                                Checked = [];
                            OneList[oneActive].subList.splice(index, 1); // 更新企业类型中一级服务中数据.
                            this.state.ThreeList = [];      //删除一级服务后清空三级服务

                            for (let key in CheckedList) {
                                if (CheckedList[key].parentId !== removeTwoDicId) {
                                    void Checked.push(CheckedList[key])
                                }
                            }
                            this.setState({
                                TwoList: data,
                                enType_twoActive: null,
                                OneList: OneList,
                                CheckedList: Checked
                            });
                        } else {
                            let TwoList = this.state.TwoList,
                                checkedIndex = CheckedList.indexOf(removeActiveItem);
                            console.log(CheckedList);
                            //根据dicid去checked里面找，然后删除  // 注意，以下使用indeof判断，必须对象必须是引用类型，否则找不到;
                            checkedIndex >= 0 && CheckedList.splice(checkedIndex, 1);
                            TwoList[twoActive].subList.splice(index, 1);
                            this.setState({ThreeList: data, TwoList: TwoList, CheckedList: CheckedList});
                        }

                    } else {
                        message.error(`${_data.value}，出现错误，请刷新页面或重试`)
                    }
                }
            }
        )
    }

    //modal ok
    EnterType_ok(is_modal_enterType) {
        this.setState({is_modal_enterType});
        console.log("ok");
    }

    //modal cancel
    EnterType_cancel(is_modal_enterType) {
        this.setState({is_modal_enterType});
    }

    //确定
    conmirBtn() {
        let data = this.state.OneList[this.state.enType_oneActive],
            SubData = [];
        // push新数组
        for (let item of this.state.CheckedList) {
            SubData.push(item.dicId);
        }
        this.setState({showEnType: data.name, SubData: SubData.join(",")}, () => {
            console.log(this.state.SubData);
        });
        this.props.updaChecked(this.state.SubData,this.state.enType_oneActive);
        this.EnterType_ok(false);  //取消
    }

    saveInputRef = input => this.input = input;
    saveInputRef_1 = input => this.input_1 = input;

    render() {
        const {Sty} = this.props;
        const {
            inputVisible,
            inputVisible_1,
            newTagName,
            enType_oneActive,
            enType_twoActive,
            enType_ThreeActive,
            is_modal_enterType,
            OneList,
            TwoList,
            ThreeList,
            CheckedList,
            showEnType
        } = this.state;

///asdasdasdsa
        return <div>

            <span className="re_font--MicYaHei" style={{position: "absolute", left: "64px", top: "194px",fontSize:14}}>企业类型</span>

            <p style={Sty.p_companytype}>{showEnType}</p>

            <span onClick={() => this.handleModaEnterTypeClick(true)}
                  className="type" style={{
                width: 29, height: 32, position: "absolute", left: "430px", top: "185px",
                cursor: "pointer", fontSize: "30px", lineHeight: "15px"
            }}/>


            <Modal
                visible={is_modal_enterType}
                onOk={() => this.EnterType_ok(false)}
                width={840}
                onCancel={() => this.EnterType_cancel(false)}
                style={{marginTop: 8, width: 820}}
                className='enType_Modal'
                footer={null}
            >
                <div className="enter_type_modal">
                    <header className="enter_type_header">
                        <p> 企业类型 </p>
                    </header>
                    <div className="enter_type_content">
                        <div className="enter_type_side _side">
                            <span className="_left enter_type_tit"> 企业类型 </span>
                            <_Select size="large"  style={{width: 120}}
                                     onChange={this.oneTypeSelect}
                                     value={OneList.length === 0 ? "" : OneList[enType_oneActive].name}
                            >
                                {
                                    OneList.map((item, index) =>
                                        <_Option key={item.dicId} value={String(index)}> {item.name} </_Option>
                                    )
                                }
                            </_Select>
                        </div>
                        <div className="main_conm_side _side">
                            <span className="_left enter_type_tit"> 主要服务 </span>
                            <div className="service_container _left">
                                <div className={classNames({service_header: true})}>
                                    {/*.ant-tag*/}
                                    <ul className="service_list _left">
                                        {
                                            TwoList.map((item, index) =>
                                                <li key={item.dicId}>
                                                    <div data-show="true" className={classNames({
                                                        "ant-tag": true,
                                                        active: enType_twoActive === index
                                                    })}
                                                         onClick={() => this.handleEnTypeTwoActive(index)}
                                                    >
                                                        <span className="ant-tag-text">{item.name}</span>

                                                        {item.enid != 0 && <i className="anticon anticon-cross"
                                                                              onClick={(e) => this.handleDeleteService(index, 2, e)}></i>}
                                                    </div>
                                                </li>
                                            )
                                        }
                                        <li>
                                            {
                                                inputVisible && (
                                                    <Input
                                                        ref={this.saveInputRef}
                                                        type="text" size="small"
                                                        style={{width: 60, borderRadius: 7}}
                                                        value={newTagName}
                                                        onChange={(e) => this.handleNewTagChange(e)}
                                                        onBlur={() => this.handleInputConfirm(OneList[enType_oneActive].dicId, 2)}
                                                        onPressEnter={() => this.handleInputConfirm(OneList[enType_oneActive].dicId, 2)}
                                                    />
                                                )
                                            }
                                            {
                                                !inputVisible && <Button size="small" type="dashed"
                                                                         onClick={(e) => this.handleInputShowClick(true)}>+
                                                    新增</Button>
                                            }
                                        </li>
                                    </ul>
                                </div>
                                <div className="service_content_list">

                                    <ul className="service_business_list">
                                        {
                                            ThreeList.map((item, index) =>
                                                <li
                                                    key={item.dicId}
                                                    className={ classNames({
                                                        "ant-tag": true,
                                                        "ant-tag-checkable": true,
                                                        active: (enType_ThreeActive.indexOf(item.dicId) > -1)
                                                    })}
                                                    onClick={() => {
                                                        this.handleEnTypeThreeActive(index)
                                                    }}
                                                >{item.name}
                                                    {
                                                        item.enid != 0 && <i className="icon_incre"
                                                                             onClick={(e) => this.handleDeleteService(index, 3, e)}> </i>
                                                    }
                                                </li>
                                            )
                                        }
                                        <li style={{border: "none"}}
                                            className={classNames({hide: enType_twoActive === null})}>
                                            {
                                                inputVisible_1 && (
                                                    <Input
                                                        ref={this.saveInputRef_1}
                                                        type="text" size="small"
                                                        style={{width: 60, borderRadius: 7}}
                                                        value={newTagName}
                                                        onChange={(e) => this.handleNewTagChange(e)}
                                                        onBlur={() => this.handleInputConfirm(TwoList[enType_twoActive].dicId, 3)}
                                                        onPressEnter={() => this.handleInputConfirm(TwoList[enType_twoActive].dicId, 3)}
                                                    />
                                                )
                                            }
                                            {
                                                !inputVisible_1 && <Button size="small" type="dashed"
                                                                           onClick={(e) => this.handleInputShowClick_1(true)}>+
                                                    新增</Button>

                                            }
                                        </li>
                                    </ul>
                                </div>
                                <p className="alarm" style={{marginTop: 5}}>
                                    {

                                        CheckedList.length === 0 ? <span> 当前您没有选择任何服务。 </span> :
                                            <div>
                                                已选择：
                                                {
                                                    CheckedList.map((item, index) =>
                                                        <span key={index}> {item.name} </span>
                                                    )
                                                }
                                            </div>

                                    }
                                </p>
                            </div>
                        </div>

                        <div className="enterType_modal_confirm">
                            <span onClick={this.conmirBtn}> 确定 </span>
                        </div>
                    </div>
                </div>
            </Modal>

        </div>
    }
}